﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeadVinaglue.Models.ViewPages;
using System.Configuration;
using System.IO;
using LeadVinaglue.Models;
using LeadVinaglue.Repository;

namespace LeadVinaglue.Areas.Management.Controllers
{
    public class BannerListController : Controller
    {
        // Create an instance of user manage
        LeadVinaglue.Repository.BannerManagementRepository repository = new LeadVinaglue.Repository.BannerManagementRepository();
        public static string BannerImagesURL = ConfigurationManager.AppSettings["BannerImagesURL"].ToString();

        // GET: /Management/Home/
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Index()
        {
            BannerManagementModel model = new BannerManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", 10, 1);

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Fillter(string keywords, string groupId, string optionId, string paymentId, string positionId, string startDate, string endDate, int pageSize, int pageIndex, int id, string sortBy, string sortOrder)
        {
            BannerManagementModel model = new BannerManagementModel();

            // Parse data
            string[] groups = groupId.Split(',');
            string[] options = optionId.Split(',');
            string[] payments = paymentId.Split(',');
            string[] position = positionId.Split(',');

            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", keywords, groups, options, payments, position, startDate, endDate, sortBy, sortOrder, pageSize, pageIndex, id);

            return Json(model);
        }
        
        // GET: /Management/Home/
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Add()
        {
            BannerManagementModel model = new BannerManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", 0);

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Add(FormCollection form)
        {
            Banner model = new Banner();
            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);

            // Set common info
            model.Title = form["Title"].ToString();
            model.ShortDesc = form["ShortDesc"].ToString();
            model.LongDesc = form["LongDesc"].ToString();
            model.ImageURL = form["ImageURL"].ToString();
            model.FlashURL = form["FlashURL"].ToString();
            model.VideoURL = form["VideoURL"].ToString();
            model.WebsiteUrl = form["WebsiteURL"].ToString();
            decimal isPrice;
            if (decimal.TryParse(form["ListPrice"].ToString(), out isPrice))
            {
                model.ListPrice = Convert.ToDecimal(form["ListPrice"].ToString());
            }
            model.UnitPrice = form["UnitPrice"].ToString();
            decimal isDiscount;
            if (decimal.TryParse(form["Discount"].ToString(), out isDiscount))
            {
                model.Discount = Convert.ToDouble(form["Discount"].ToString());
            }
            model.Active = (form["Active"] != null && form["Active"].ToString() == "on");

            // Group /payment items
            model.GroupID = form["GroupID"].ToString();
            model.PaymentID = int.Parse(form["PaymentID"].ToString());

            // Option
            var optionId = int.Parse(form["OptionID"].ToString());
            model.OptionID = optionId;
            if (optionId > 0)
            {
                var opt = new BannerOptionManagementRepository().GetSingle(optionId);
                if (opt != null)
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(form["StartDate"].ToString(), out dateTime))
                        model.StartDate = Convert.ToDateTime(form["StartDate"].ToString());
                    else
                        model.StartDate = DateTime.Now;
                    model.EndDate = Convert.ToDateTime(model.StartDate).AddDays(opt.LongTimeValue.Value);
                }
            }

            // position
            var positionId = form["PositionID"].ToString();
            model.PositionID = positionId;
            if (positionId != "-1")
            {
                var pos = new BannerPositionManagementRepository().GetSingle(positionId);
                if (pos != null)
                {
                    model.Width = (form["Width"] != null && int.Parse(form["Width"].ToString()) > 0) ? int.Parse(form["Width"].ToString()) : pos.Width.Value;
                    model.Height = (form["Height"] != null && int.Parse(form["Height"].ToString()) > 0) ? int.Parse(form["Height"].ToString()) : pos.Width.Value;
                }
            }

            model.CreatedByUserID = user.ID;

            repository.Create(model);

            return RedirectToAction("Index", "BannerList");
        }

        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Edit(int id)
        {
            BannerManagementModel model = new BannerManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", id);

            ViewBag.BannerId = id;

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Edit(int id, FormCollection form)
        {
            Banner model = repository.GetSingle(id);

            if (model != null)
            {
                // Set common info
                model.Title = form["Title"].ToString();
                model.ShortDesc = form["ShortDesc"].ToString();
                model.LongDesc = form["LongDesc"].ToString();
                model.ImageURL = form["ImageURL"].ToString();
                model.FlashURL = form["FlashURL"].ToString();
                model.VideoURL = form["VideoURL"].ToString();
                model.WebsiteUrl = form["WebsiteURL"].ToString();
                decimal isPrice;
                if (decimal.TryParse(form["ListPrice"].ToString(), out isPrice))
                {
                    model.ListPrice = Convert.ToDecimal(form["ListPrice"].ToString());
                }
                model.UnitPrice = form["UnitPrice"].ToString();
                decimal isDiscount;
                if (decimal.TryParse(form["Discount"].ToString(), out isDiscount))
                {
                    model.Discount = Convert.ToDouble(form["Discount"].ToString());
                }
                
                model.Active = (form["Active"] != null && form["Active"].ToString() == "on");

                // Group /payment items
                model.GroupID = form["GroupID"].ToString();
                model.PaymentID = int.Parse(form["PaymentID"].ToString());

                // Option
                var optionId = int.Parse(form["OptionID"].ToString());
                model.OptionID = optionId;
                if (optionId > 0)
                {
                    var opt = new BannerOptionManagementRepository().GetSingle(optionId);
                    if (opt != null)
                    {
                        DateTime dateTime;
                        if (DateTime.TryParse(form["StartDate"].ToString(), out dateTime))
                            model.StartDate = Convert.ToDateTime(form["StartDate"].ToString());
                        else
                            model.StartDate = DateTime.Now;
                        model.EndDate = Convert.ToDateTime(model.StartDate).AddDays(opt.LongTimeValue.Value);
                    }
                }

                // position
                var positionId = form["PositionID"].ToString();
                model.PositionID = positionId;
                if (positionId != "-1")
                {
                    var pos = new BannerPositionManagementRepository().GetSingle(positionId);
                    if (pos != null)
                    {
                        //model.Width = pos.Width.Value;
                        //model.Height = pos.Height.Value;

                        model.Width = (form["Width"] != null && int.Parse(form["Width"].ToString()) > 0) ? int.Parse(form["Width"].ToString()) : pos.Width.Value;
                        model.Height = (form["Height"] != null && int.Parse(form["Height"].ToString()) > 0) ? int.Parse(form["Height"].ToString()) : pos.Width.Value;
                    }
                }

                repository.Update(model);
            }

            return RedirectToAction("Index", "BannerList");
        }
        
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            string fileName = string.Empty;
            UploadModel model = new UploadModel();

            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(BannerImagesURL), fileName);
                fileData.SaveAs(path);

                model.FileName = fileName;
                model.FilePath = string.Format("{0}/{1}", BannerImagesURL, fileName);
            }

            // redirect back to the index action to show the form once again
            return Json(model);
        }

        [HttpPost]
        public ActionResult UploadFlash(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            string fileName = string.Empty;
            UploadModel model = new UploadModel();

            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(BannerImagesURL), fileName);
                fileData.SaveAs(path);

                model.FileName = fileName;
                model.FilePath = string.Format("{0}/{1}", BannerImagesURL, fileName);
            }

            // redirect back to the index action to show the form once again
            return Json(model);
        }

        [HttpPost]
        public ActionResult UploadVideo(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            string fileName = string.Empty;
            UploadModel model = new UploadModel();

            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(BannerImagesURL), fileName);
                fileData.SaveAs(path);

                model.FileName = fileName;
                model.FilePath = string.Format("{0}/{1}", BannerImagesURL, fileName);
            }

            // redirect back to the index action to show the form once again
            return Json(model);
        }
    }
}
